<template>
  <t-link
    v-permission="['system:permission:assign-user-role']"
    theme="primary"
    @click="handleOpenDialog('update', { ...props.row, userId: props.row.id, associationCompany: [] })"
  >
    分配角色
  </t-link>
  <!-- 自定义对话框 -->
  <custom-dialog
    ref="customDialogRef"
    v-slot="{ formData }"
    :api-map="{ get: getRoleByUserId, update: setUserRole }"
    header="分配角色"
  >
    <t-form-item label="用户账号" name="username" :rules="[{ required: true, message: '请输入用户账号' }]">
      <t-input v-model:value="formData.username" placeholder="请输入用户账号" clearable readonly />
    </t-form-item>
    <t-form-item label="用户昵称" name="nickname" :rules="[{ required: true, message: '请输入用户昵称' }]">
      <t-input v-model:value="formData.nickname" placeholder="请输入用户昵称" clearable readonly />
    </t-form-item>
    <t-form-item label="角色" name="roleIds">
      <t-select
        v-model:value="formData.roleIds"
        :options="simpleRoleList"
        :keys="{ value: 'id', label: 'name' }"
        placeholder="请选择角色"
        clearable
        filterable
        multiple
        @clear="formData.roleIds = []"
      />
    </t-form-item>
    <t-form-item label="归属公司" name="associationCompany">
      <t-select
        v-model:value="formData.associationCompany"
        :options="companyList"
        :keys="{ value: 'id', label: 'name' }"
        placeholder="请选择归属公司"
        clearable
        filterable
        multiple
        @clear="formData.associationCompany = null"
      />
    </t-form-item>
  </custom-dialog>
</template>

<script setup lang="ts">
import { MessagePlugin } from 'tdesign-vue-next';
import { ref, useTemplateRef } from 'vue';

import { getCompanyList } from '@/api/system/dept';
import { getRoleByUserId, getSimpleRoleList, setUserRole } from '@/api/system/role';
import CustomDialog from '@/components/custom/dialog/index.vue';

// props
const props = defineProps({
  row: {
    type: Object,
    default: () => ({}),
  },
});
// 精简角色列表
const simpleRoleList = ref([]);
// 处理获取精简角色列表
const handleGetSimpleRoleList = () => {
  getSimpleRoleList()
    .then((data) => {
      simpleRoleList.value = data;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 公司列表
const companyList = ref([]);
// 处理获取公司列表
const handleGetCompanyList = () => {
  getCompanyList()
    .then((data) => {
      companyList.value = data;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  handleGetSimpleRoleList();
  handleGetCompanyList();
  customDialogRef.value.open(mode, params);
};
</script>

<style lang="less" scoped></style>
